<template>
  <div class="image-upload">
    <el-upload
      :class="{ 'image-uploader': !multiple, 'image-list': multiple }"
      :action="uploadUrl"
      :headers="headers"
      :show-file-list="multiple"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :file-list="fileList"
      :list-type="multiple ? 'picture-card' : ''"
      :multiple="multiple"
    >
      <template v-if="!multiple">
        <img v-if="modelValue" :src="modelValue" class="uploaded-image" />
        <el-icon v-else class="upload-icon"><Plus /></el-icon>
      </template>
      <template v-else>
        <el-icon class="upload-icon"><Plus /></el-icon>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  multiple: {
    type: Boolean,
    default: false
  },
  fileList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'update:fileList', 'success', 'error', 'remove'])

const userStore = useUserStore()

// 上传地址
const uploadUrl = 'http://localhost:8080/dms/merchant/product/image/upload'

// 请求头，携带token
const headers = computed(() => ({
  Authorization: `Bearer ${userStore.token}`
}))

// 上传前验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功
const handleSuccess = (response, file) => {
  if (response.code === 200) {
    if (!props.multiple) {
      // 单图模式
      emit('update:modelValue', response.data)
    }
    emit('success', response.data, file)
    ElMessage.success('上传成功')
  } else {
    handleError(new Error(response.message || '上传失败'))
  }
}

// 上传失败
const handleError = (error) => {
  console.error('上传失败:', error)
  emit('error', error)
  ElMessage.error('上传失败：' + (error.message || '未知错误'))
}

// 删除图片
const handleRemove = (file) => {
  emit('remove', file)
}
</script>

<style lang="scss" scoped>
.image-upload {
  .image-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    
    &:hover {
      border-color: var(--el-color-primary);
    }
    
    .uploaded-image {
      width: 178px;
      height: 178px;
      display: block;
      object-fit: cover;
    }
    
    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      line-height: 178px;
    }
  }

  .image-list {
    :deep(.el-upload--picture-card) {
      width: 148px;
      height: 148px;
      line-height: 148px;
    }

    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 148px;
      height: 148px;
    }

    .upload-icon {
      font-size: 28px;
      color: #8c939d;
    }
  }
}
</style> 